import {
	baseUrl
} from '@/common/baseUrl.js';

const DEFAULT_METHOD = 'GET';
const ERROR_MESSAGES = {
	401: '未授权',
	404: '未找到',
	DEFAULT: 'API 错误'
};

const showToast = (title) => {
	uni.showToast({
		title,
		icon: 'none'
	});
};

const showLoading = () => {
	uni.showLoading({
		title: '加载中...'
	});
};

const hideLoading = () => {
	uni.hideLoading();
};

const removeTokenAndNavigateToLogin = () => {
	uni.removeStorageSync('logintoken');
	setTimeout(() => {
		uni.navigateTo({
			url: '/pages/login/login'
		});
	}, 1000);
};

const handleResponse = (res, hideLoading) => {
	if (!hideLoading) {
		hideLoading();
	}

	if (res.statusCode === 401) {
		removeTokenAndNavigateToLogin();
		return null;
	}
	if (res.statusCode === 404) {
		showToast(ERROR_MESSAGES[res.statusCode] || ERROR_MESSAGES.DEFAULT);
		return null;
	}
	if (res.statusCode !== 200) {
		showToast(ERROR_MESSAGES[res.statusCode] || ERROR_MESSAGES.DEFAULT);
		return null;
	}

	if (res.data.code !== '200') {
		if (res.data.code === 401 || res.data.code === 402) {
			removeTokenAndNavigateToLogin();
			return null;
		}
		showToast(res.data.msg);
		return null;
	}

	return res.data;
};

export const http = (param = {}) => {
	const {
		url,
		method = DEFAULT_METHOD,
		data = {},
		token = '',
		hideLoading = false
		isJson = false
	} = param;

	const requestUrl = baseUrl + url;
	const Authorization = uni.getStorageSync('logintoken') || '';
	const header = {
		'Accept': 'application/json',
		'content-type': method.toUpperCase() === 'POST' && !isJson ? 'application/x-www-form-urlencoded' :
			'application/json'
	};

	if (Authorization) {
		header['Authorization'] = Authorization;
	}

	if (!hideLoading) {
		showLoading();
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: requestUrl,
			method: method.toUpperCase(),
			data,
			header,
			success: (res) => {
				const responseData = handleResponse(res, hideLoading);
				if (responseData) {
					resolve(responseData);
				} else {
					reject(res);
				}
			},
			fail: (e) => {
				if (!hideLoading) {
					hideLoading();
				}
				showToast(e.errMsg || ERROR_MESSAGES.DEFAULT);
				reject(e);
			},
			complete: () => {
				if (!hideLoading) {
					hideLoading();
				}
			}
		});
	});
};